iT邦幫忙

2024 iThome 鐵人賽

DAY 10
0
Mobile Development

肯定會斷賽之在 Android 開發使用設計模式系列 第 10

113/10 - 合成模式(Composite)- Java

  • 分享至 

  • xImage
  •  

介紹

看了後才知道這個是用來做樹狀結構的,今天比較趕,就隨便寫寫,內容應該會有錯

合成模式實作

public abstract class AbstractMemberManagement {
    
    protected String name;

    public AbstractMemberManagement(String name) {
        this.name = name;
    }

    public abstract void add(AbstractMemberManagement memberManagement);

    public abstract void remove(AbstractMemberManagement memberManagement);

    public abstract void displayLevel();
}

public class Store extends AbstractMemberManagement {
    private List<AbstractMemberManagement> memberManagementList = new ArrayList<>();

    public Store(String name) {
        super(name);
    }

    @Override
    public void add(AbstractMemberManagement memberManagement) {
        memberManagementList.add(memberManagement);
    }

    @Override
    public void remove(AbstractMemberManagement memberManagement) {
        memberManagementList.remove(memberManagement);
    }

    @Override
    public void displayLevel() {
        for (AbstractMemberManagement abstractMemberManagement : memberManagementList) {
            abstractMemberManagement.displayLevel();
        }
    }
}
public abstract class Card extends AbstractMemberManagement{

    public Card(String name) {
        super(name);
    }

    @Override
    public void add(AbstractMemberManagement memberManagement) {
        Log.d("Tag", "會員卡Card無法再增加節點");
    }

    @Override
    public void remove(AbstractMemberManagement memberManagement) {
        Log.d("Tag", "會員卡Card沒有可以移除的節點");
    }

    @Override
    public void displayLevel() {

    }
}
public class Gold extends Card {

    public Gold(String name) {
        super(name);
    }

    @Override
    public void displayLevel() {
        super.displayLevel();
        Log.d("Tag", "金卡使用者" + name + "您好");
    }
}
public class Silver extends Card {

    public Silver(String name) {
        super(name);
    }

    @Override
    public void displayLevel() {
        super.displayLevel();
        Log.d("Tag", "銀卡使用者" + name + "您好");
    }
}

上一篇
113/09 - 原型模式(Prototype)- Kotlin
下一篇
113/11 - 合成模式(Composite)- Kotlin
系列文
肯定會斷賽之在 Android 開發使用設計模式30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言